package com.xy.hms.controller;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import com.xy.hms.sdk.WXPay;
import com.xy.hms.sdk.XyWXPayConfig;
import io.goeasy.GoEasy;
import io.swagger.annotations.Api;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author xiaye
 * @create 2020-05-14-9:40
 */
@Controller
@RequestMapping("wxpay")
@Api(tags = "微信支付")
public class WxPayController {

    @RequestMapping("showpay")
    public String showPayment(){
        return "mypay";
    }


    @RequestMapping("createPayment")
    @ResponseBody
    public void doPay(HttpServletResponse response){

        //        用于生成订单编号的随机数
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHssmm");
        String orderIdPrefix = sdf.format(date);//创建订单编号的前缀
        String pid = "2011";//商品id
        String orderId1 = orderIdPrefix+pid;



        //1.创建配置类对象
        XyWXPayConfig config = new XyWXPayConfig();
        //2.创建支付对象
        WXPay wxpay = null;
        try {
            wxpay = new WXPay(config);
            //3.将一些元数据存入到map集合中
            Map<String, String> data = new HashMap<String, String>();
            data.put("body", "房间订单支付");
            data.put("out_trade_no", orderId1);//订单编号
            data.put("device_info", "");//设备信息
            data.put("fee_type", "CNY");//货币单位： 分
            data.put("total_fee", "1");// 1分
            data.put("spbill_create_ip", "123.12.12.123");//对于这样123.12.12.123IP地址将会被记录
            //******需要有一个回调的接口，获取此次微信支付的信息。
            data.put("notify_url", "http://uk9w8d.natappfree.cc/wxpay/notify_url");
            data.put("trade_type", "NATIVE");  // 此处指定为扫码支付
            data.put("product_id", "1");//商品ID

            Map<String, String> resp = wxpay.unifiedOrder(data);
            //二维码的链接   code_url
            String code_url = resp.get("code_url");

            //生成二维码

            //二维码需要包含的文本内容
            HashMap<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>();
            hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
            hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);
            hints.put(EncodeHintType.MARGIN, 2);
            try {
                BitMatrix bitMatrix = new MultiFormatWriter().encode(code_url, BarcodeFormat.QR_CODE, 200, 200, hints);
                MatrixToImageWriter.writeToStream(bitMatrix, "PNG", response.getOutputStream());
                System.out.println("创建二维码完成");
            } catch (Exception e) {
                e.printStackTrace();
            }

            GoEasy goEasy = new GoEasy("https://rest-hangzhou.goeasy.io", "BC-c9dab1704aed49e0b47167c344029704");

            //放一个订单号
            //推送
            goEasy.publish("pay", "支付成功");


        } catch (Exception e) {
            e.printStackTrace();
        }

    }




        /**
         * 支付回调接口
         * @param request
         * @param response
         * @throws IOException
         */
    @RequestMapping("notify_url")
    @ResponseBody
    public void getNotifyUrl(HttpServletRequest request, HttpServletResponse response) throws IOException {
        ServletInputStream inputStream = request.getInputStream();

        byte[] bytes = new byte[1024];
        int len = 0;
        while((len=inputStream.read(bytes))!=-1){
            String s = new String(bytes, 0, len);
            System.out.println(s);
        }

        response.getWriter().write(
                "<xml> <return_code><![CDATA[SUCCESS]]></return_code> <return_msg><![CDATA[OK]]></return_msg> </xml>"
        );
    }
}
